<template>
  <a-layout-content class="flex flex-col lg:h-full relative w-full">
    <a-card :bordered="false">
      <a-row v-if="tool.getDevice() === 'mobile'">
        <a-col :xs="24" :sm="8">
          <a-form :model="requestParams" style="padding: 20px 0;">
            <a-row :gutter="16">
              <a-col :xs="24" :sm="24" :md="8">
                <a-form-item field="name" label="直播间名称">
                  <a-input v-model="requestParams.name" placeholder="请输入直播间名称" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="8">
                <a-form-item field="room_id" label="直播间ID">
                  <a-input v-model="requestParams.room_id" placeholder="请输入直播间ID" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="8">
                <a-form-item field="live_status" label="直播状态">
                  <a-select v-model="requestParams.live_status" :options="types" allow-clear placeholder="请选择直播状态" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-col :xs="24" :sm="8" :style="{ textAlign: 'right', marginBottom: '15px' }">
          <a-space direction="horizontal" :size="20">
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <icon-search />
              </template>
              {{ options.searchText || '搜索' }}
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ options.resetText || '重置' }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-row v-else>
        <a-col :flex="1">
          <a-form :model="requestParams" ref="searchFormRef" :auto-label-width="true">
            <a-row :gutter="10">
              <a-col :xs="24" :sm="24" :md="8">
                <a-form-item field="name" label="直播间名称">
                  <a-input v-model="requestParams.name" placeholder="请输入直播间名称" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="8">
                <a-form-item field="room_id" label="直播间ID">
                  <a-input v-model="requestParams.room_id" placeholder="请输入直播间ID" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="8">
                <a-form-item  label="直播状态">
                  <a-select v-model="requestParams.live_status" :options="types" allow-clear placeholder="请选择直播状态" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider v-if="!singleLine" style="height: 84px" direction="vertical" />
        <a-col :flex="singleLine ? '185px' : '80px'" :style="{ textAlign: 'right' }">
          <a-space :direction="!singleLine ? 'vertical' : 'horizontal'" :size="singleLine ? 10 : 20">
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <icon-search />
              </template>
              {{ options.searchText || '搜索' }}
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ options.resetText || '重置' }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-row>
        <a-col>
          <a-popover trigger="click" position="bl" style="width: 120px" @change="handleClickChange" :visible="clicked">
            <a-button type="primary" size="small">
              创建直播/点播
            </a-button>
            <template #content>
              <div id="tableSetting">
                <div class="title cursor-pointer " @click="openLive('add','1')"> 创建直播 </div>
                <div class="title cursor-pointer mt-1" @click="openBroad('add','1')"> 创建定时直播 </div>
              </div>
            </template>
          </a-popover>
          <a-button type="primary" size="small" @click="openRewardList(0)" style="margin-left: 10px;">
            奖励设置
          </a-button>
        </a-col>
      </a-row>
    </a-card>
      <div class="gutter-example mt-3" style="max-height: 69vh;overflow: hidden;overflow-y: scroll;">
        <a-row :gutter="16">
          <a-col class="gutter-row" :xs="24" :sm="12" :md="8" :lg="6" :xl="6" :xxl="4"  v-for="(item,index) in tableData.data" :key="index">
            <div class="gutter-box bg-white p-1">
              <div class="relative">
                <img :src="item.cover" alt="" class="w-full h-48 object-fit">
                <div class="absolute top-0 right-0">
                  <div class="flex  box-card">
                    <div class="liveTag">{{item.status_name}}</div>
                    <div class="liveTag">{{['竖屏','横屏'][item.show_type]}}</div>
                    <div class="liveTag">{{['','直播','定时'][item.room_type]}}</div>
                  </div>
                  
                </div>
              </div>
              <div class="text-md text--gray-600 font-bold m-1 ellipsis-2">[{{item.room_id}}]{{item.name}}</div>
              <div class="text-sm text-gray-500 m-1">{{item.start_time}}</div>
              <a-row class="ml-1 mr-1 flex flex-align" style="justify-content: space-between;">
                <a-col :span="10" class="flex justify-between">
                  <div class="m-1 cursor-pointer">
                    <a-tooltip content="点名奖励设置">
                      <sa-icon icon="IconPlayArrow" :size="18" />
                    </a-tooltip>
                  </div>
                  <div class="m-1 cursor-pointer" @click="openRewardList(item.room_id)">
                    <a-tooltip content="基础奖励设置">
                      <sa-icon icon="IconSettings" :size="18" />
                    </a-tooltip>
                  </div>
                  <div class="m-1 cursor-pointer" @click="handleLink(item.room_id)">
                    <a-tooltip content="控制台">
                      <sa-icon icon="IconComputer" :size="18" />
                    </a-tooltip>
                  </div>
                  <div class="m-1 cursor-pointer" @click="goUrl('app/marketing/watchLog',item.room_id)">
                    <a-tooltip content="观看记录">
                      <sa-icon icon="IconFile" :size="18" />
                    </a-tooltip>
                  </div>
                  <div class="m-1 cursor-pointer">
                    <a-tooltip content="观看链接">
                      <sa-icon icon="IconShareAlt" :size="18" />
                    </a-tooltip>
                  </div>
                  <div class="m-1 cursor-pointer" @click="goUrl('app/marketing/signNameLogs',item.room_id)">
                    <a-tooltip content="点名记录">
                      <sa-icon icon="IconStamp" :size="18" />
                    </a-tooltip>
                  </div>
                </a-col>
                <a-col :span="4" class="flex justify-end">
                  <a-popover trigger="click" position="br" v-model="clicked" @change="handleClickChange">
                    <sa-icon class="cursor-pointer" icon="IconMore" :size="18" />
                    <template #content>
                      <div id="tableSetting">
                        <div class="title cursor-pointer " @click="openLive('edit',item)"> 编辑 </div>
                        <div class="title cursor-pointer mt-1 "> 
                          <a-popconfirm
                              content="确定要删除该直播间吗?"
                              position="bottom"
                              @ok="deleteRoom(item)">
                              <div> 删除</div>
                            </a-popconfirm>  
                        </div>
                        <div class="title cursor-pointer mt-1 " @click="handleLink(item.room_id, 1)"> 控制台2 </div>
                        <div class="title cursor-pointer mt-1 " @click="openPlayback(item)"> 回放设置 </div>
                        <div class="title cursor-pointer mt-1 " @click="handleStatisticsLink(item.room_id)"> 数据统计 </div>
                        <div class="title cursor-pointer mt-1 " @click="goUrl('app/marketing/signLog',item.room_id)"> 签到记录 </div>
                        <div class="title cursor-pointer mt-1 " @click="copyLive(item)"> 复制多节直播 </div>
                      </div>
                    </template>
                  </a-popover>
                  
                </a-col>
              </a-row>
            </div>
          </a-col>
        </a-row>
      </div>
      
      <div class="mt-3 text-right fixed bottom-1 right-0 bg-white p-1" v-if="tableData.total > 0" style="width: 100%;">
        <a-pagination
          :total="tableData.total"
          show-total
          show-jumper
          show-page-size
          :page-size-options="options.pageSizeOption"
          @page-size-change="pageSizeChangeHandler"
          @change="pageChangeHandler"
          v-model:current="requestParams['page']"
          :page-size="requestParams['limit']"
          style="display: inline-flex" />
      </div>
    <EditLive ref="editLiveRef"  @success="handleReset" />
    <CopyMultiplePopup ref="copyMultiplePopupRef" @success="handleReset" />
    <Broadcast ref="BroadcastRef" @success="handleReset" />
    <PlaybackPopup ref="playbackPopupRef" @success="handleReset" />
    <RewardList ref="rewardListRef" @success="handleReset" />
    <a-modal
      title="温馨提示"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="visible = false"
    >
      <p>当前流量不足，是否继续创建直播间</p>
    </a-modal>
  </a-layout-content> 
</template>
<script setup lang="ts">
import { onMounted, openBlock, reactive, ref } from 'vue'
import tool from '@/utils/tool'
import API_LIVE from '@/api/live/live'
import EditLive from './editLive.vue'
import CopyMultiplePopup from './CopyMultiplePopup.vue'
import Broadcast from './Broadcast.vue'
import { Message } from '@arco-design/web-vue'
import PlaybackPopup from './playbackPopup.vue'
import RewardList from './rewardlist.vue'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
onMounted(() => {
  getPageLists()
})
const handleSearch = () => {
  console.log(requestParams.value)
  requestParams.value['page'] = 1
  requestParams.value['limit'] = options.value.pageSize
  getPageLists()
}
const options = ref({
  searchText: '搜索',
  resetText: '重置',
  pageSizeOption: [10, 20, 30, 40],
  pageSize: 20,
})
const singleLine = ref(true)
const editLiveRef = ref()
const BroadcastRef = ref()
const copyMultiplePopupRef = ref()
const playbackPopupRef = ref()
const clicked = ref(false)
const visible = ref(false)
const confirmLoading = ref(false)
const types = [
  { label: '未开播', value: 1 },
  { label: '直播中', value: 2 },
  { label: '已结束', value: 3 },
]

const handleClickChange = (visible) => {
  clicked.value = false
}
const selectType = ref(0)
const openLive = async (mode,item) => {
  clicked.value = false
  if(mode=='add'){
    const res = await API_LIVE.flowRate({ room_id: item.room_id })
    if(res.data.info<res.data.max){
      visible.value = true
      selectType.value = 0
    }else{
      editLiveRef.value.open(mode,item)
    }
  }else if(item.room_type == 1&&mode=='edit'){
    editLiveRef.value.open(mode,item)
  }else if(item.room_type == 2&&mode=='edit'){
    BroadcastRef.value.open(mode,item)
  }
}

const handleOk = () => {
  visible.value = false
  if(selectType.value==0){
    editLiveRef.value.open('add',{})
  }else if(selectType.value==1){
    BroadcastRef.value.open('add',{})
  }
}

const openBroad = async (mode,item) => {
  const res = await API_LIVE.flowRate({ room_id: item.room_id })
  if(res.data.info<res.data.max){
      visible.value = true
      selectType.value = 1
    }else{
      BroadcastRef.value.open(mode,item)
    }
}

const goUrl = (path:string,room_id:any) => {
//  跳转到路由app/marketing/signLog?room_id=${room_id}
router.push({ name: path, query: { room_id: room_id } })
}

const copyLive = (item) => {
  copyMultiplePopupRef.value.open(item)
}

const rewardListRef = ref()

const openRewardList = (item) => {
  rewardListRef.value?.open()
  rewardListRef.value?.setFormData(item)
}

const deleteRoom = async (item) => {
   const resp = await API_LIVE.deleteRoom({ room_id: item.room_id })
    if (resp.code === 200) {
      Message.success('删除成功')
      handleReset()
    }
}

// 控制台
const handleLink = async (room_id: any, index = 0) => {
    const link = ['/console/index.html?room_id=', '/console/urltwo.html?room_id=']
    window.open(`${link[index]}${room_id}`, '_blank')
}

// 数据统计
const handleStatisticsLink = async (room_id: any) => {
    const response = await API_LIVE.dataTotal({ room_id })

    if (response.data.url) {
        window.open(`${response.data.url}`, '_blank')
    }
}

const openPlayback = (item) => {
  playbackPopupRef.value.open('add')
  playbackPopupRef.value.setFormData(item)
}

const handleReset = () => {
  requestParams.value = {
    page: 1,
    limit: options.value.pageSize,
    name: '',
    room_id: '',
    live_status: '',
  }
  getPageLists()
}

const getPageLists = async () => {
  const res = await API_LIVE.getPageList(requestParams.value)
  if (res.code === 200) {
    tableData.value.total = res.data.total
    tableData.value.data = res.data.list
  }
}

const tableData = ref<any>({
  total: 0,
  data: [],
})
const requestParams = ref({
  page: 1,
  limit: options.value.pageSize,
  name: '',
  room_id: '',
  live_status: '',
})


// 页码变化
const pageChangeHandler = async (currentPage) => {
  console.log(currentPage)
  requestParams.value['page'] = currentPage
  await refresh()
}

// 每页数量变化
const pageSizeChangeHandler = async (pageSize) => {
  requestParams.value['page'] = 1
  requestParams.value['limit'] = pageSize
  await refresh()
}

const refresh = async () => {
  getPageLists()
  // await requestData()
  //tableRef.value?.selectAll(false)
}

</script>
<style scoped lang="less">
  .livesList {
    width: 100%;
    height: 100%;
  }
  .gutter-row{margin-bottom: 10px;}
  .flex-align {
    align-items: center;
  }
  .box-card{
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 10px;
    padding: 3px 8px;
    border-radius: 20px;margin: 5px 5px 0 0 ;
    display: flex;justify-content: flex-end;align-items: center;
    .liveTag{
      margin: 0 5px;padding-right:7px;position: relative;
      &:last-child{
        border-right: none;margin-right: 0;
      }
      &:last-child::after{
        background: none;
      }
    }
    .liveTag::after{
      content: '';
      position: absolute;
      top: 50%;
      right: 0;
      transform: translateY(-50%);
      width: 1px;
      height: 8px;
      border-radius: 50%;
      background-color: #fff;
    }

}
</style>
